<script setup>

import {computed, nextTick, onMounted, ref, watch} from "vue";

import CronTabSecond from "./second.vue";
import CronTabMinute from "./minute.vue";
import CronTabHour from "./hour.vue";
import CronTabDay from "./day.vue";
import CronTabMonth from "./month.vue";
import CronTabWeek from "./week.vue";
import CronTabYear from "./year.vue";
import CronTabResult from "./result.vue";

const props = defineProps({
  hideComponent: {
    type: Array,
    default: () => [],
  },
  expression: {
    type: String,
    default: ''
  }
})

const cronSecond = ref();
const cronMinute = ref();
const cronHour = ref();
const cronDay = ref();
const cronMonth = ref();
const cronWeek = ref();
const cronYear = ref();
const emit = defineEmits(['fill']);

const tabTitles = ref(["秒", "分钟", "小时", "日", "月", "周", "年"]);
const tabActive = ref(0);
const hideComponent = ref([])
// const myIndex = ref(0);
const crontabValueObj = ref({
  second: '*',
  minute: '*',
  hour: '*',
  day: '*',
  month: '*',
  week: '?',
  year: '',
})

const crontabValueString = computed(() => {
  const obj = crontabValueObj.value
  return obj.second
      + " "
      + obj.minute
      + " "
      + obj.hour
      + " "
      + obj.day
      + " "
      + obj.month
      + " "
      + obj.week
      + (obj.year === "" ? "" : " " + obj.year)
})

const modalRef = ref();

const handleSubmit = async () => {
  emit('fill', crontabValueString.value);
  modalRef.value.handleClose();
}

const handleOpen = () => {
  modalRef.value.handleOpen();
  nextTick(()=>{
    if(props.expression){
      resolveExp();
    }
  })
}

const updateCrontabValue = (name, value, from) => {
  crontabValueObj.value[name] = value;
  if(from && from !== name){
    changeRadio(name, value);
  }
}

const checkNumber = (value, min, max) => {
  value = Math.floor(value);
  if (value < min) {
    value = min;
  } else if (value > max) {
    value = max;
  }
  return value;
}

// 赋值到组件
const changeRadio = (name, value) => {
  let mapRef = {
    second: cronSecond,
    minute: cronMinute,
    hour: cronHour,
    day: cronDay,
    month: cronMonth,
    week: cronWeek,
    year: cronYear
  }
  let arr = ["second", "minute", "hour", "month"],
      refName = mapRef[name],
      insValue;

  if (!refName.value) return;

  if (arr.includes(name)) {
    if (value === "*") {
      insValue = 1;
    } else if (value.indexOf("-") > -1) {
      let indexArr = value.split("-");
      isNaN(indexArr[0])
          ? (refName.value.cycle01 = 0)
          : (refName.value.cycle01 = Number(indexArr[0]));
      refName.value.cycle02 = Number(indexArr[1]);
      insValue = 2;
    } else if (value.indexOf("/") > -1) {
      let indexArr = value.split("/");
      isNaN(indexArr[0])
          ? (refName.value.avg01 = 0)
          : (refName.value.avg01 = Number(indexArr[0]));
      refName.value.avg02 = Number(indexArr[1]);
      insValue = 3;
    } else {
      insValue = 4;
      refName.value.checkboxList = value.split(",");
    }
  } else if (name === "day") {
    if (value === "*") {
      insValue = 1;
    } else if (value === "?") {
      insValue = 2;
    } else if (value.indexOf("-") > -1) {
      let indexArr = value.split("-");
      isNaN(indexArr[0])
          ? (refName.value.cycle01 = 0)
          : (refName.value.cycle01 = Number(indexArr[0]));
      refName.value.cycle02 = Number(indexArr[1]);
      insValue = 3;
    } else if (value.indexOf("/") > -1) {
      let indexArr = value.split("/");
      isNaN(indexArr[0])
          ? (refName.value.avg01 = 0)
          : (refName.value.avg01 = Number(indexArr[0]));
      refName.value.avg02 = Number(indexArr[1]);
      insValue = 4;
    } else if (value.indexOf("W") > -1) {
      let indexArr = value.split("W");
      isNaN(indexArr[0])
          ? (refName.value.workday = 0)
          : (refName.value.workday = Number(indexArr[0]));
      insValue = 5;
    } else if (value === "L") {
      insValue = 6;
    } else {
      refName.value.checkboxList = value.split(",");
      insValue = 7;
    }
  } else if (name === "week") {
    if (value === "*") {
      insValue = 1;
    } else if (value === "?") {
      insValue = 2;
    } else if (value.indexOf("-") > -1) {
      let indexArr = value.split("-");
      isNaN(indexArr[0])
          ? (refName.value.cycle01 = 0)
          : (refName.value.cycle01 = Number(indexArr[0]));
      refName.value.cycle02 = Number(indexArr[1]);
      insValue = 3;
    } else if (value.indexOf("#") > -1) {
      let indexArr = value.split("#");
      isNaN(indexArr[0])
          ? (refName.value.avg01 = 1)
          : (refName.value.avg01 = Number(indexArr[0]));
      refName.value.avg02 = Number(indexArr[1]);
      insValue = 4;
    } else if (value.indexOf("L") > -1) {
      let indexArr = value.split("L");
      isNaN(indexArr[0])
          ? (refName.value.weekday = 1)
          : (refName.value.weekday = Number(indexArr[0]));
      insValue = 5;
    } else {
      refName.value.checkboxList = value.split(",");
      insValue = 6;
    }
  } else if (name === "year") {
    if (value === "") {
      insValue = 1;
    } else if (value === "*") {
      insValue = 2;
    } else if (value.indexOf("-") > -1) {
      insValue = 3;
      let indexArr = value.split("-");
      isNaN(indexArr[0])
          ? (refName.value.cycle01 = 0)
          : (refName.value.cycle01 = Number(indexArr[0]));
      refName.value.cycle02 = Number(indexArr[1]);
    } else if (value.indexOf("/") > -1) {
      let indexArr = value.split("/");
      isNaN(indexArr[0])
          ? (refName.value.avg01 = 0)
          : (refName.value.avg01 = Number(indexArr[0]));
      refName.value.avg02 = Number(indexArr[1]);
      insValue = 4;
    } else {
      refName.value.checkboxList = value.split(",");
      insValue = 5;
    }
  }
  refName.value.radioValue = insValue;
}

// 清空表达式
const clearCron = () => {
  crontabValueObj.value = {
    second: "*",
    minute: "*",
    hour: "*",
    day: "*",
    month: "*",
    week: "?",
    year: "",
  };
  for (let j in crontabValueObj.value) {
    changeRadio(j, crontabValueObj.value[j]);
  }
}

// 反解析表达式
const resolveExp = () => {
  if(props.expression){
    let arr = props.expression.split(" ");
    if(arr.length >= 6){
      // 6位以上是合法表达式
      let obj = {
        second: arr[0],
        minute: arr[1],
        hour: arr[2],
        day: arr[3],
        month: arr[4],
        week: arr[5],
        year: arr[6] ? arr[6] : "",
      };
      crontabValueObj.value = {
        ...obj
      };
      for (let i in obj) {
        if(obj[i]) changeRadio(i,obj[i]);
      }
    }
  }else{
    // 否则还原
    clearCron();
  }
}

watch(()=>props.expression,resolveExp)

onMounted(() => {
  resolveExp();
})

defineExpose({handleOpen})

</script>

<template>
  <dialog-form ref="modalRef" modal-title="Cron表达式生成器" modalWidth="1000px" @submit="handleSubmit">
    <el-tabs type="border-card">
      <el-tab-pane label="秒">
        <CronTabSecond
            @update="updateCrontabValue"
            :check="checkNumber"
            :cron="crontabValueObj"
            ref="cronSecond"/>
      </el-tab-pane>
      <el-tab-pane label="分钟">
        <CronTabMinute
            @update="updateCrontabValue"
            :check="checkNumber"
            :cron="crontabValueObj"
            ref="cronMinute"/>
      </el-tab-pane>
      <el-tab-pane label="小时">
        <CronTabHour
            @update="updateCrontabValue"
            :check="checkNumber"
            :cron="crontabValueObj"
            ref="cronHour"/>
      </el-tab-pane>
      <el-tab-pane label="日">
        <CronTabDay
            @update="updateCrontabValue"
            :check="checkNumber"
            :cron="crontabValueObj"
            ref="cronDay"/>
      </el-tab-pane>
      <el-tab-pane label="月">
        <CronTabMonth
            @update="updateCrontabValue"
            :check="checkNumber"
            :cron="crontabValueObj"
            ref="cronMonth"/>
      </el-tab-pane>
      <el-tab-pane label="周">
        <CronTabWeek
            @update="updateCrontabValue"
            :check="checkNumber"
            :cron="crontabValueObj"
            ref="cronWeek"/>
      </el-tab-pane>
      <el-tab-pane label="年">
        <CronTabYear
            @update="updateCrontabValue"
            :check="checkNumber"
            :cron="crontabValueObj"
            ref="cronYear"/>
      </el-tab-pane>
    </el-tabs>

    <div class="popup-main">
      <div class="popup-result">
        <p class="title">时间表达式</p>
        <table>
          <thead>
          <tr>
            <th v-for="item of tabTitles" width="40" :key="item">{{ item }}</th>
            <th>Cron 表达式</th>
          </tr>
          </thead>
          <tbody>
          <tr>
            <td>
              <span>{{ crontabValueObj.second }}</span>
            </td>
            <td>
              <span>{{ crontabValueObj.minute }}</span>
            </td>
            <td>
              <span>{{ crontabValueObj.hour }}</span>
            </td>
            <td>
              <span>{{ crontabValueObj.day }}</span>
            </td>
            <td>
              <span>{{ crontabValueObj.month }}</span>
            </td>
            <td>
              <span>{{ crontabValueObj.week }}</span>
            </td>
            <td>
              <span>{{ crontabValueObj.year }}</span>
            </td>
            <td>
              <span>{{ crontabValueString }}</span>
            </td>
          </tr>
          </tbody>
        </table>
      </div>
      <CronTabResult :ex="crontabValueString"></CronTabResult>
    </div>
    <!--    <vue3-cron-plus-picker/>-->

    <template #reset-btn>
      <el-button type="warning" @click="clearCron">重置</el-button>
    </template>
  </dialog-form>
</template>
<style scoped>
.pop_btn {
  text-align: center;
  margin-top: 20px;
}
.popup-main {
  position: relative;
  margin: 10px auto;
  background: #fff;
  border-radius: 5px;
  font-size: 12px;
  overflow: hidden;
}
.popup-title {
  overflow: hidden;
  line-height: 34px;
  padding-top: 6px;
  background: #f2f2f2;
}
.popup-result {
  box-sizing: border-box;
  line-height: 24px;
  margin: 25px auto;
  padding: 15px 10px 10px;
  border: 1px solid #ccc;
  position: relative;
}
.popup-result .title {
  position: absolute;
  top: -28px;
  left: 50%;
  width: 140px;
  font-size: 14px;
  margin-left: -70px;
  text-align: center;
  line-height: 30px;
  background: #fff;
}
.popup-result table {
  text-align: center;
  width: 100%;
  margin: 0 auto;
}
.popup-result table span {
  display: block;
  width: 100%;
  font-family: arial;
  line-height: 30px;
  height: 30px;
  white-space: nowrap;
  overflow: hidden;
  border: 1px solid #e8e8e8;
}
.popup-result-scroll {
  font-size: 12px;
  line-height: 24px;
  height: 10em;
  overflow-y: auto;
}
</style>
